package presentation;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import db.Album;
import db.DbUtils;

@SuppressWarnings("unchecked")
public class PresentationsBean {
	public static String getHTMLlink4album(Long albumID, long userID) {
		if(albumID == null) {
			return "";
		}
		Session session = DbUtils.startSession();
		String albumPath = DbUtils.getAlbumPath(session, albumID);
		String[] albums = albumPath.split("/");
		if(albums.length == 1) {
			return "/<a href=\"EnterInAlbumServlet?album_id=" + 
			DbUtils.getALbumIdByName(session, albums[0], userID) + "\">" + albums[0] + "</a>";
		}
		StringBuilder HTMLlink = new StringBuilder();
		for(int i = 0; i < albums.length; i++) {
			HTMLlink.append("/<a href=\"EnterInAlbumServlet?album_id=");
			HTMLlink.append(DbUtils.getALbumIdByName(session, albums[i], userID));
			HTMLlink.append("\">");
			HTMLlink.append(albums[i]);
			HTMLlink.append("</a>");
		}
		return HTMLlink.toString();
	}
	
	public static List<Album> getTopLevelAlbumsByUser(long userId,int pageNumber) {
		Session session = DbUtils.startSession();
		Query query = session.createQuery("from db.Album where AlbumParentId is null and UserId = :userid");
		query.setLong("userid", userId);
		int page = pageNumber -1;
		query.setFirstResult(page * 16);
		query.setMaxResults(16);
		return query.list();
	}
	public static List<Album> getTopLevelAlbumsByUser(long userId) {
		Session session = DbUtils.startSession();
		Query query = session.createQuery("from db.Album where AlbumParentId is null and UserId = :userid");
		query.setLong("userid", userId);
		return query.list();
	}
	
	public static long getTopLevelAlbumsByUserNum(long userId) {
		Session session = DbUtils.startSession();
		Query query = session.createQuery("from db.Album where AlbumParentId is null and UserId = :userid");
		query.setLong("userid", userId);
		List<Album> albums=query.list();
		long allAlb = albums.size();
		long page;
		if (allAlb < 16) {
			page = 1;
		} else {
			if (allAlb % 16 != 0) {
				page = (allAlb / 16) + 1;
			} else {
				page = (allAlb / 16);
			}
		}
		return page;
	}

}
